package quotation.web.user.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import quotation.exception.BusinessException;
import quotation.utils.JwtUtil;
import quotation.utils.Md5Util;
import quotation.web.invite.service.InviteService;
import quotation.web.user.ddd.entity.UserEntity;
import quotation.web.user.ddd.form.LoginForm;
import quotation.web.user.mapper.UserMapper;
import quotation.web.user.service.UserService;

import java.util.concurrent.TimeUnit;

/**
 * @author lyx
 * @date 2025/2/19
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {


    public static final String USER_TOKEN_PREFIX = "user_token_";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private InviteService inviteService;

    @Override
    public String openIdLogin(String openId, String inviteCode) {

        UserEntity one = this.lambdaQuery().eq(UserEntity::getOpenId, openId)
                .one();


        //不存在的用户自动注册，存在邀请码的用户，自动转正
        if (one == null) {
            one = this.initializationDefault(openId, inviteCode);
        }
        String token = JwtUtil.generateToken(one.getId(), one.getUsertype(), one.getName());
        stringRedisTemplate.opsForValue().set(USER_TOKEN_PREFIX + one.getId(), token, 2, TimeUnit.HOURS);

        return token;
    }

    @Transactional(rollbackFor = Exception.class)
    public UserEntity initializationDefault(String openId, String inviteCode) {

        boolean validate = false;
        if (StrUtil.isNotEmpty(inviteCode)) {
            validate = inviteService.validate(inviteCode);
        }

        UserEntity user = UserEntity.builder()
                .account(openId)
                .name("微信用户")
                .passwd(Md5Util.md5(openId))
                .usertype(BooleanUtil.toInt(validate))
                .build();

        this.save(user);
        return user;
    }


    @Override
    public String login(LoginForm form) {
        UserEntity one = this.lambdaQuery().eq(UserEntity::getAccount, form.getAccount())
                .one();
        if (one == null) {
            throw new BusinessException("账号或密码错误");
        }

        if (!one.getPasswd().equals(form.getPasswd())) {
            throw new BusinessException("账号或密码错误");
        }
        String token = JwtUtil.generateToken(one.getId(), one.getUsertype(), one.getName());
        stringRedisTemplate.opsForValue().set(USER_TOKEN_PREFIX + one.getId(), token, 2, TimeUnit.HOURS);

        return token;
    }

}
